package com.etc.service;

import com.etc.common.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;

/**
 * @author Chen
 * @since 2021/1/17 - 0:15
 */
@Service
@PropertySource("classpath:mail.properties")
public class EmailService {
	private static Logger loger = LoggerFactory.getLogger(EmailService.class);
	@Autowired
	@Qualifier("javaMailSender")
	JavaMailSenderImpl javaMailSender;
	// 发送邮箱通过配置文件的方式引入
	@Value("${mail.smtp.username}")
	String emailSender;

	/**
     * 发送邮件服务： 默认 text格式
	 * @param title  主题
	 * @param content 内容
	 * @param receivers 接收者数组
	 * @throws ServiceException
	 */
	public void sendMail(String title, String content, String ...receivers) throws ServiceException {
		// 限制群发人数
		if (receivers.length >= 5) {
			throw new ServiceException("发送人数过多");
		} else {
			loger.debug("接收人是？？？" + String.valueOf(receivers));
			SimpleMailMessage mail = new SimpleMailMessage();
			// 设置邮件标题
			mail.setSubject(title);
			// 设置邮件内容
			mail.setText(content);

			mail.setFrom(emailSender);
			// 设置邮件收件人
			mail.setTo(receivers);
			new Thread(){
				@Override
				public void run() {
					javaMailSender.send(mail);
				}
			}.start();
		}
	}
}